const mysql = require('mysql2/promise')
const bcrypt = require('bcryptjs')

async function addMoreUsers () {
  let connection

  try {
    connection = await mysql.createConnection({
      host: 'localhost',
      port: 3306,
      user: 'root',
      password: 'GKL9512357',
      database: 'novel_platform',
      charset: 'utf8mb4'
    })

    console.log('📝 添加更多测试用户...')

    // 首先更新现有用户为管理员
    await connection.query(
      "UPDATE users SET role = 'admin' WHERE email = '1477042095@qq.com'"
    )
    console.log('✅ 更新现有用户为管理员')

    // 测试用户数据
    const testUsers = [
      {
        username: 'admin001',
        email: 'admin@novel.com',
        password: 'admin123',
        nickname: '超级管理员',
        role: 'admin',
        is_vip: 1,
        coins: 1000,
        level: 10
      },
      {
        username: 'user001',
        email: 'user1@test.com',
        password: 'password123',
        nickname: '测试用户1',
        role: 'user',
        is_vip: 0,
        coins: 100,
        level: 2
      },
      {
        username: 'user002',
        email: 'user2@test.com',
        password: 'password123',
        nickname: '测试用户2',
        role: 'user',
        is_vip: 1,
        coins: 200,
        level: 5,
        vip_expire_date: '2025-12-31 23:59:59'
      },
      {
        username: 'vipuser001',
        email: 'vip@novel.com',
        password: 'vip123',
        nickname: 'VIP用户',
        role: 'user',
        is_vip: 1,
        coins: 500,
        level: 8,
        vip_expire_date: '2025-12-31 23:59:59'
      },
      {
        username: 'moderator001',
        email: 'moderator@novel.com',
        password: 'mod123',
        nickname: '版主用户',
        role: 'moderator',
        is_vip: 1,
        coins: 300,
        level: 6
      },
      {
        username: 'user003',
        email: 'user3@test.com',
        password: 'password123',
        nickname: '普通用户3',
        role: 'user',
        is_vip: 0,
        coins: 50,
        level: 1
      },
      {
        username: 'user004',
        email: 'user4@test.com',
        password: 'password123',
        nickname: '普通用户4',
        role: 'user',
        is_vip: 0,
        coins: 80,
        level: 3
      },
      {
        username: 'vipuser002',
        email: 'vip2@novel.com',
        password: 'vip456',
        nickname: 'VIP用户2',
        role: 'user',
        is_vip: 1,
        coins: 800,
        level: 12,
        vip_expire_date: '2026-06-30 23:59:59'
      },
      {
        username: 'user005',
        email: 'user5@test.com',
        password: 'password123',
        nickname: '活跃用户',
        role: 'user',
        is_vip: 0,
        coins: 150,
        level: 4
      },
      {
        username: 'user006',
        email: 'user6@test.com',
        password: 'password123',
        nickname: '新手用户',
        role: 'user',
        is_vip: 0,
        coins: 20,
        level: 1
      }
    ]

    for (const user of testUsers) {
      try {
        // 检查用户是否已存在
        const [existing] = await connection.query(
          'SELECT id FROM users WHERE email = ?',
          [user.email]
        )

        if (existing.length > 0) {
          console.log(`⚠️  用户 ${user.email} 已存在，跳过`)
          continue
        }

        // 加密密码
        const hashedPassword = await bcrypt.hash(user.password, 12)

        // 插入用户
        await connection.query(
          `INSERT INTO users (username, email, password_hash, nickname, role, is_vip, coins, level, vip_expire_date, status)
           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')`,
          [
            user.username,
            user.email,
            hashedPassword,
            user.nickname,
            user.role,
            user.is_vip,
            user.coins,
            user.level,
            user.vip_expire_date || null
          ]
        )

        console.log(
          `✅ 添加用户: ${user.email} (${user.role}) - ${user.nickname}`
        )
      } catch (error) {
        console.error(`❌ 添加用户 ${user.email} 失败:`, error.message)
      }
    }

    // 显示用户统计
    const [statsRows] = await connection.query(`
      SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN is_vip = 1 THEN 1 ELSE 0 END) as vip_count,
        SUM(CASE WHEN role = 'admin' THEN 1 ELSE 0 END) as admin_count,
        SUM(CASE WHEN role = 'moderator' THEN 1 ELSE 0 END) as moderator_count,
        SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active_count
      FROM users
    `)

    const stats = statsRows[0]
    console.log('\n📊 用户统计:')
    console.log(`   总用户数: ${stats.total}`)
    console.log(`   活跃用户: ${stats.active_count}`)
    console.log(`   VIP用户: ${stats.vip_count}`)
    console.log(`   管理员: ${stats.admin_count}`)
    console.log(`   版主: ${stats.moderator_count}`)

    // 显示所有用户列表
    const [allUsers] = await connection.query(`
      SELECT id, username, email, nickname, role, is_vip, level, coins, created_at
      FROM users 
      ORDER BY id
    `)

    console.log('\n👥 所有用户列表:')
    allUsers.forEach(user => {
      console.log(
        `  ID: ${user.id}, ${user.username} (${user.email}) - ${
          user.nickname
        } [${user.role}] VIP:${user.is_vip ? '是' : '否'} 等级:${
          user.level
        } 金币:${user.coins}`
      )
    })

    console.log('\n🎉 用户数据添加完成！')
  } catch (error) {
    console.error('❌ 操作失败:', error.message)
  } finally {
    if (connection) {
      await connection.end()
    }
  }
}

addMoreUsers()
